package com.cloud.music.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.cloud.music.utils.CookieUtil;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Aspect
@Component
public class CookieInjectAspect {

    /**
     * 设置注入cookie，在注解的位置切入代码
     */
    @Pointcut("@annotation(com.cloud.music.annotation.CookieInject) || @within(com.cloud.music.annotation.CookieInject)")
    public void cookieInjectPointCut() {
    }

    @Before("cookieInjectPointCut()")
    public void doBefore() {
        // 获取request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        // 获取cookie
        CookieUtil.setCurrentCookie(request.getHeader("Cookie"));
    }

    @After("cookieInjectPointCut()")
    public void doAfter() {
        // 获取response
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = Objects.requireNonNull(attributes).getResponse();
        if (ObjectUtil.isNotNull(response)) {
            // 获取响应响应头
            response.setHeader("Cookie", CookieUtil.getCurrentCookie());
        }
        // 清除cookie
        CookieUtil.remove();
    }
}
